package com.topisv.tms.rest.qimen.qmservice;

import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXB;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.repository.EdiGoodsSkuDao;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.repository.EdiOrderItemDao;
import com.topisv.tms.repository.work.WorkOrderDao;
import com.topisv.tms.rest.qimen.qmentity.request.stockoutConfirm.Batch;
import com.topisv.tms.rest.qimen.qmentity.request.stockoutConfirm.DeliveryOrder;
import com.topisv.tms.rest.qimen.qmentity.request.stockoutConfirm.Item;
import com.topisv.tms.rest.qimen.qmentity.request.stockoutConfirm.OrderLine;
import com.topisv.tms.rest.qimen.qmentity.request.stockoutConfirm.Package;
import com.topisv.tms.rest.qimen.qmentity.request.stockoutConfirm.PackageMaterial;
import com.topisv.tms.rest.qimen.qmentity.request.stockoutConfirm.StockOutConfirm;
import com.topisv.tms.rest.qimen.qmsend.QmRequestSender;
import com.topisv.tms.rest.qimen.request.RequestMethodType;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.utils.InitProperties;
import com.topisv.tms.utils.rule.TMSTransportRule;
@Component
@Transactional(readOnly =  false)
public class StockoutConfirmService extends QmRequestSender<String> {

	private static final Logger logger = LoggerFactory.getLogger(StockoutConfirmService.class);
	@Autowired
	private EdiOrderDao ediOrderDao;
	@Autowired
	private EdiOrderItemDao ediOrderItemDao;
	@Autowired
	private WorkOrderDao workOrderDao;
	@Autowired
	private EdiGoodsSkuDao ediGoodsSkuDao;
	@Override
	protected RequestParams setupParam(RequestParams sendParams) {
		Map<String,String> params = new HashMap<String,String>();
		params.put("method", RequestMethodType.STOCK_OUT_CONFIRM.getType());
		params.put("format", InitProperties.get("qm.format"));
		params.put("app_key", InitProperties.get("regAppKey"));
		params.put("v", InitProperties.get("qm.v"));
		params.put("sign_method", InitProperties.get("qm.sign_method"));
		params.put("customerId", "");//暂未定
		sendParams.setSecret(InitProperties.get("regAppSecret"));
		sendParams.setParams(params);
		return sendParams;
	}

	@SuppressWarnings("unused")
	@Override
	protected String execute(String orderno,RequestParams sendParams) {
		SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String sendXml = null;
		StockOutConfirm stockOutConfirm = new StockOutConfirm();
		// 数据组装
		Map<String,EdiGoodsSku> cacheSku = new HashMap<String,EdiGoodsSku>();
		EdiOrder ediOrder = ediOrderDao.findByOrdeno(orderno);
		WorkOrder workOrder = workOrderDao.findByOrder(ediOrder.getOrdeno());
		
		if(null == ediOrder){
			logger.info("ediOrder is not exist");
			return sendXml;
		}
		sendParams.getParams().put("customerId", ediOrder.getCustomerCode());
		
		logger.info("出库确认");
		DeliveryOrder deliveryOrder = new DeliveryOrder();
		deliveryOrder.setTotalOrderLines("");
		deliveryOrder.setDeliveryOrderCode(ediOrder.getCustomerOrdeno());
		deliveryOrder.setDeliveryOrderId(ediOrder.getOrdeno());
		deliveryOrder.setWarehouseCode(ediOrder.getWarehouseCode());
		deliveryOrder.setOrderType(ediOrder.getDeliveryOrderType());
		deliveryOrder.setOutBizCode(TMSTransportRule.generateByPreFixAndSuffix("QM","DOCS"));
		//暂时只支持一次发货完成
		deliveryOrder.setConfirmType("0");
		deliveryOrder.setLogisticsCode(workOrder.getExpressCompany());
		deliveryOrder.setLogisticsName(workOrder.getExpressName());
		deliveryOrder.setStatus("DELIVERED");
		
		if("ebill".equals(workOrder.getBillType())){
			deliveryOrder.setExpressCode(workOrder.getEbillNo());

		}else {
			deliveryOrder.setExpressCode(workOrder.getExpressNo());
		}
		
		deliveryOrder.setOrderConfirmTime(formatDate.format(new Date()));
		stockOutConfirm.setDeliveryOrder(deliveryOrder);
		
		logger.info("--设置package");
		List<Package> pkgList = new ArrayList<Package>();
		Package pkg = new Package();
		
		pkg.setLogisticsName(workOrder.getExpressName());
		
		if("ebill".equals(workOrder.getBillType())){
			pkg.setExpressCode(workOrder.getEbillNo());

		}else {
			pkg.setExpressCode(workOrder.getExpressNo());
		}
		
		pkg.setPackageCode("");
		pkg.setLength("0");
		pkg.setWidth("0");
		pkg.setHeight("0");
		pkg.setWeight("0");
		pkg.setVolume("0");
		
		logger.info("------设置PackageMaterial");
		List<PackageMaterial> materialList = new ArrayList<PackageMaterial>();
		PackageMaterial material = new PackageMaterial();
		material.setQuantity("0");
		material.setType("");
		materialList.add(material);
		
		pkg.setPackageMaterial(materialList);
		
		logger.info("------设置items");
		List<Item>  itemList = new ArrayList<Item>();
		logger.info("------设置OrderLine");
		List<OrderLine> orderLines = new ArrayList<OrderLine>();
		List<EdiOrderItem> ediOrderItemList = ediOrderItemDao.findByOrdeno(ediOrder.getOrdeno());
		if(ediOrderItemList!=null){
			for (int i = 0; i < ediOrderItemList.size(); i++) {
				EdiOrderItem ediOrderItem = ediOrderItemList.get(i);		
				EdiGoodsSku ediGoodsSku = this.getEdiGoodsSku(ediOrder.getCustomerCode(), ediOrderItem.getSku(), cacheSku);
				
				if (ediGoodsSku==null) {
					ediGoodsSku = new EdiGoodsSku();
				}
				Item packageItem = new Item();
				packageItem.setItemCode(ediGoodsSku.getBar());
				packageItem.setItemId(ediGoodsSku.getId().toString());
				packageItem.setQuantity(ediOrderItem.getQty().toString());
				itemList.add(packageItem);
				
				
				OrderLine orderLine = new OrderLine();
				orderLine.setOutBizCode(TMSTransportRule.generateByPreFixAndSuffix("QM","DOCS"));
				orderLine.setOrderLineNo(ediOrderItem.getLineNo());
				orderLine.setItemCode(ediGoodsSku.getBar());
				orderLine.setItemId(ediGoodsSku.getId().toString());
				orderLine.setItemName(ediGoodsSku.getSkuName());
				orderLine.setInventoryType("");
				orderLine.setActualQty(ediOrderItem.getQty().toString());
				//--------------未处理
				orderLine.setBatchCode("");
				orderLine.setProductDate("");
				orderLine.setExpireDate("");
				orderLine.setProduceCode("");
				
				List<Batch> batchList = new ArrayList<Batch>();
				//设置batch节点
				Batch batch = new Batch();
				batch.setBatchCode("");
				batch.setProductDate("");
				batch.setExpireDate("");
				batch.setProduceCode("");
				batch.setInventoryType("");
				batch.setActualQty("");
				orderLine.setBatch(batchList);
				
				orderLines.add(orderLine);
			}
		}
		
		pkg.setItem(itemList);
		pkgList.add(pkg);
		stockOutConfirm.setPackage(pkgList);
		stockOutConfirm.setOrderLine(orderLines);		
		StringWriter writer = new StringWriter();
		JAXB.marshal(stockOutConfirm,writer);
		sendXml = writer.toString();
		logger.info("出库确认成功");
		return sendXml;
	}

	public EdiGoodsSku getEdiGoodsSku(String customerCode,String sku,Map<String,EdiGoodsSku> cacheSku){
		EdiGoodsSku ediGoodsSku = null;
		if(cacheSku.get(customerCode+"_"+sku) != null){
			ediGoodsSku = cacheSku.get(customerCode+"_"+sku);
		}else {
			ediGoodsSku = ediGoodsSkuDao.findByCustomerCodeAndSku(customerCode ,sku);
		}
		return ediGoodsSku;
	}
}
